package xyz.doikki.dkplayer.widget.component;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.eventbus.EventBus;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.IGestureComponent;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.L;
import xyz.doikki.videoplayer.util.PlayerUtils;

import static xyz.doikki.videoplayer.util.PlayerUtils.stringForTime;

public class TikTokView02 extends FrameLayout
        implements IGestureComponent,View.OnClickListener{

    private final ImageView mPlayBtn;



    private final ProgressBar mBottomProgress;

    private ControlWrapper mControlWrapper;



    private boolean mIsDragging;

    private boolean mIsShowBottomProgress = true;



    private final ImageView mIcon;
    private final ProgressBar mProgressPercent;
    private final TextView mTextPercent;

    private final LinearLayout mCenterContainer;


    private int mStartX, mStartY;

    public TikTokView02(@NonNull Context context) {
        super(context);
    }

    public TikTokView02(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TikTokView02(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {


        LayoutInflater.from(getContext()).inflate(R.layout.layout_tiktok_controller02, this, true);

        mPlayBtn = findViewById(R.id.play_btn);




        mIcon = findViewById(R.id.iv_icon);
        mProgressPercent = findViewById(R.id.pro_percent);
        mTextPercent = findViewById(R.id.tv_percent);
        mCenterContainer = findViewById(R.id.center_container);


        mBottomProgress = findViewById(R.id.bottom_progress);



//        setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mControlWrapper.togglePlay();
//            }
//        });




//        mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }


    @Override
    public void attach(@NonNull ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public View getView() {
        return this;
    }


    /**
     * 是否显示底部进度条，默认显示
     */
    public void showBottomProgress(boolean isShow) {
        mIsShowBottomProgress = isShow;
    }





    @Override
    public void onVisibilityChanged(boolean isVisible, Animation anim) {

        if (isVisible) {

            if (mIsShowBottomProgress) {
                mBottomProgress.setVisibility(GONE);
            }
        } else {

            if (mIsShowBottomProgress) {
                mBottomProgress.setVisibility(VISIBLE);
                AlphaAnimation animation = new AlphaAnimation(0f, 1f);
                animation.setDuration(300);
                mBottomProgress.startAnimation(animation);
            }
        }

    }

    @Override
    public void onPlayStateChanged(int playState) {

        if (playState == VideoView.STATE_IDLE
                || playState == VideoView.STATE_START_ABORT
                || playState == VideoView.STATE_PREPARING
                || playState == VideoView.STATE_PREPARED
                || playState == VideoView.STATE_ERROR
                || playState == VideoView.STATE_PLAYBACK_COMPLETED) {
            mCenterContainer.setVisibility(GONE);
        } else {
            //mCenterContainer.setVisibility(VISIBLE);
        }
        switch (playState) {
            case VideoView.STATE_IDLE:
            case VideoView.STATE_PLAYBACK_COMPLETED:

                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);

                break;
            case VideoView.STATE_START_ABORT:
            case VideoView.STATE_PREPARING:
            case VideoView.STATE_PREPARED:
            case VideoView.STATE_ERROR:

                break;
            case VideoView.STATE_PLAYING:

                mPlayBtn.setVisibility(GONE);
                if (mIsShowBottomProgress) {
                    if (mControlWrapper.isShowing()) {
                        mBottomProgress.setVisibility(GONE);

                    } else {

                        mBottomProgress.setVisibility(VISIBLE);
                    }
                }

                //开始刷新进度
                mControlWrapper.startProgress();

                break;
            case VideoView.STATE_PAUSED:
                mPlayBtn.setVisibility(VISIBLE);
                L.e("STATE_PAUSED " + hashCode());
                break;
            case VideoView.STATE_BUFFERING:
                // 停止刷新进度
                mControlWrapper.stopProgress();
                break;
            case VideoView.STATE_BUFFERED:
                //开始刷新进度
                mControlWrapper.startProgress();
                break;
        }
    }




    @Override
    public void onPlayerStateChanged(int playerState) {

        Activity activity = PlayerUtils.scanForActivity(getContext());
        if (activity != null && mControlWrapper.hasCutout()) {
            int orientation = activity.getRequestedOrientation();
            int cutoutHeight = mControlWrapper.getCutoutHeight();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {

                mBottomProgress.setPadding(0, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {

                mBottomProgress.setPadding(cutoutHeight, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {

                mBottomProgress.setPadding(0, 0, cutoutHeight, 0);
            }
        }

    }

    @Override
    public void setProgress(int duration, int position) {

        if (mIsDragging) {
            return;
        }
        if (duration > 0) {

            int pos = (int) (position * 1.0 / duration * mBottomProgress.getMax());
//            if((duration-position)<=1000){
//
//                Log.d("TAGStartStrag", "setProgress: 到1000了:"+pos);
//            }
            if(mBottomProgress.getMax()-pos<50){
                Log.d("TAGStartStrag", "setProgress: 到1000了:"+pos);
            }

            mBottomProgress.setProgress(pos);

            Log.d("TAGStartStrag", "setProgress: pos:"+pos);
            Log.d("TAGStartStrag", "setProgress: position:"+position);
            Log.d("TAGStartStrag", "setProgress: duration:"+duration);


        }
        int percent = mControlWrapper.getBufferedPercentage();
        if (percent >= 95) { //解决缓冲进度不能100%问题
            mBottomProgress.setSecondaryProgress(mBottomProgress.getMax());
        } else {
            mBottomProgress.setSecondaryProgress(percent * 10);
        }





    }




    @Override
    public void onLockStateChanged(boolean isLocked) {
        onVisibilityChanged(!isLocked, null);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_play) {
            mControlWrapper.togglePlay();
        }
    }




//    @Override
//    public void onStartTrackingTouch(SeekBar seekBar) {
//        mIsDragging = true;
//        Log.d("TAGStartStrag", "onStartTrackingTouch: 开始拖动");
//        mControlWrapper.stopProgress();
//        mControlWrapper.stopFadeOut();
//
//    }
//
//    @Override
//    public void onStopTrackingTouch(SeekBar seekBar) {
//
//        long duration = mControlWrapper.getDuration();
//        long newPosition = (duration * seekBar.getProgress()) / mBottomProgress.getMax();
//        Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 newPosition:"+newPosition);
//        Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 duration:"+duration);
//        mControlWrapper.seekTo((int) newPosition);
//        mIsDragging = false;
//        mControlWrapper.startProgress();
//        mControlWrapper.startFadeOut();
//    }
//
//
//    @Override
//    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//        if (!fromUser) {
//            return;
//        }
//
//        long duration = mControlWrapper.getDuration();
//        long newPosition = (duration * progress) / mBottomProgress.getMax();
//
//    }
//

    @Override
    public void onStartSlide() {
        mControlWrapper.hide();
        mCenterContainer.setVisibility(VISIBLE);
        mCenterContainer.setAlpha(1f);

    }

    @Override
    public void onStopSlide() {
        mCenterContainer.animate()
                .alpha(0f)
                .setDuration(300)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        mCenterContainer.setVisibility(GONE);
                    }
                })
                .start();
    }

    @Override
    public void onPositionChange(int slidePosition, int currentPosition, int duration) {
        mProgressPercent.setVisibility(GONE);
        if (slidePosition > currentPosition) {
            mIcon.setImageResource(R.drawable.dkplayer_ic_action_fast_forward);
        } else {
            mIcon.setImageResource(R.drawable.dkplayer_ic_action_fast_rewind);
        }
        mTextPercent.setText(String.format("%s/%s", stringForTime(slidePosition), stringForTime(duration)));

    }

    @Override
    public void onBrightnessChange(int percent) {
        mProgressPercent.setVisibility(VISIBLE);
        mIcon.setImageResource(R.drawable.dkplayer_ic_action_brightness);
        mTextPercent.setText(percent + "%");
        mProgressPercent.setProgress(percent);
    }

    @Override
    public void onVolumeChange(int percent) {

        mProgressPercent.setVisibility(VISIBLE);
        if (percent <= 0) {
            mIcon.setImageResource(R.drawable.dkplayer_ic_action_volume_off);
        } else {
            mIcon.setImageResource(R.drawable.dkplayer_ic_action_volume_up);
        }
        mTextPercent.setText(percent + "%");
        mProgressPercent.setProgress(percent);
    }
}
